package com.ybkj.daijia.api.weixin.tenpayv3;

import com.ybkj.daijia.api.weixin.tenpayv3.http.HttpClientConnectionManager;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.KeyStore;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

public class GetWxOrderno {

    public static DefaultHttpClient httpclient;

    static {
        httpclient = new DefaultHttpClient();
        httpclient = (DefaultHttpClient) HttpClientConnectionManager
            .getSSLInstance(httpclient);
    }

    // public static String getPayNo(String url,String xmlParam){
    //
    // CloseableHttpClient httpclient = HttpClients.createDefault();
    //
    // HttpPost httpost = new HttpPost(url);
    //
    // RequestConfig defaultRequestConfig = RequestConfig.custom()
    // .setCircularRedirectsAllowed(true)
    // .setConnectTimeout(5000)
    // .setConnectionRequestTimeout(1000)
    // .setSocketTimeout(5000).build();
    //
    // httpost.setConfig(defaultRequestConfig);
    //
    // String prepay_id = "";
    // try {
    // httpost.setEntity(new StringEntity(xmlParam, "UTF-8"));
    // CloseableHttpResponse response = httpclient.execute(httpost);
    // String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
    // Map<String, Object> dataMap = new HashMap<String, Object>();
    // System.out.println("GetWxOrderno.getPayNo()jsonStr:"+jsonStr);
    // if(jsonStr.indexOf("FAIL")!=-1){
    // return prepay_id;
    // }
    // Map<String, String> map = doXMLParse(jsonStr);
    // String return_code = map.get("return_code");
    // prepay_id = map.get("prepay_id");
    // } catch (Exception e) {
    //
    // e.printStackTrace();
    // }
    // return prepay_id;
    // }

    public static String getPayNo(String url, String xmlParam) {
        DefaultHttpClient client = new DefaultHttpClient();

        client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS,
            true);
        HttpPost httpost = HttpClientConnectionManager.getPostMethod(url);
        String prepay_id = "";
        try {

            httpclient.getParams().setParameter(
                CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
            httpclient.getParams().setParameter(
                CoreConnectionPNames.SO_TIMEOUT, 5000);

            httpost.setEntity(new StringEntity(xmlParam, "UTF-8"));
            HttpResponse response = httpclient.execute(httpost);
            String jsonStr = EntityUtils
                .toString(response.getEntity(), "UTF-8");
            Map<String, Object> dataMap = new HashMap<String, Object>();
            if (jsonStr.indexOf("FAIL") != -1) {
                return prepay_id;
            }
            Map map = doXMLParse(jsonStr);
            String return_code = (String) map.get("return_code");
            prepay_id = (String) map.get("prepay_id");
        } catch (Exception e) {

            e.printStackTrace();
        }
        return prepay_id;
    }

    public static Map<String, String> doTransfer(String url, String xmlParam) {
        CloseableHttpClient httpclient = HttpClients.custom().build();

        // DefaultHttpClient client = new DefaultHttpClient();
        // client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS,
        // true);
        HttpPost httpost = HttpClientConnectionManager.getPostMethod(url);
        Map<String, String> map = null;
        try {
            httpost.setEntity(new StringEntity(xmlParam, "UTF-8"));
            HttpResponse response = httpclient.execute(httpost);
            String jsonStr = EntityUtils
                .toString(response.getEntity(), "UTF-8");
            map = doXMLParse(jsonStr);
            return map;
        } catch (Exception e) {

            e.printStackTrace();
        }
        return map;
    }

    // public static Map<String, String> doTransfer2(String mch_id, File
    // certFile, String url,
    // String xmlParam) {
    //
    // Map<String, String> map = null;
    //
    // KeyStore keyStore = null;
    // FileInputStream instream = null;
    // try {
    // keyStore = KeyStore.getInstance("PKCS12");
    // instream = new FileInputStream(certFile);
    // keyStore.load(instream, mch_id.toCharArray());
    // } catch (Exception e) {
    //
    // e.printStackTrace();
    // } finally {
    // if (null != instream) {
    // try {
    // instream.close();
    // } catch (IOException e) {
    //
    // e.printStackTrace();
    // }
    // }
    // }
    //
    // CloseableHttpClient httpclient1 = null;
    // try {
    //
    // // Trust own CA and all self-signed certs
    // SSLContext sslcontext =
    // SSLContexts.custom().loadKeyMaterial(keyStore,
    // mch_id.toCharArray()).build();
    // // Allow TLSv1 protocol only
    // SSLConnectionSocketFactory sslsf =
    // new SSLConnectionSocketFactory(sslcontext, new String[] {"TLSv1"}, null,
    // SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    //
    // RequestConfig defaultRequestConfig = RequestConfig.custom()
    // .setSocketTimeout(5000)
    // .setConnectTimeout(5000)
    // .setConnectionRequestTimeout(5000)
    // .setStaleConnectionCheckEnabled(true)
    // .build();
    //
    // httpclient1 =
    // HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).setSSLSocketFactory(sslsf).build();
    //
    // DefaultHttpClient httpclient = (DefaultHttpClient)
    // HttpClientConnectionManager.getSSLInstance(httpclient1);
    //
    // HttpPost httpost = HttpClientConnectionManager.getPostMethod(url);
    //
    // // CloseableHttpResponse response = httpclient.execute(httpget);
    // try {
    // httpost.setEntity(new StringEntity(xmlParam, "UTF-8"));
    //
    // HttpResponse response = httpclient.execute(httpost);
    // String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
    // // String jsonStr = response.getEntity();
    // System.out.println("GetWxOrderno.doTransfer2()jsonStr:" + jsonStr);
    // map = doXMLParse(jsonStr);
    // return map;
    //
    // } catch (Exception e) {
    //
    // e.printStackTrace();
    // } finally {
    // // response.close();
    // }
    // } catch (Exception e) {
    //
    // e.printStackTrace();
    // } finally {
    // if (null != httpclient1) {
    // try {
    // httpclient1.close();
    // } catch (IOException e) {
    //
    // e.printStackTrace();
    // }
    // }
    // }
    //
    // return map;
    // }

    public static Map<String, String> doTransfer2(String mch_id, File certFile,
        String url, String xmlParam) {
        StringBuffer message = new StringBuffer();
        try {
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            FileInputStream instream = new FileInputStream(certFile);
            keyStore.load(instream, mch_id.toCharArray());
            // Trust own CA and all self-signed certs
            SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore, mch_id.toCharArray()).build();
            // Allow TLSv1 protocol only
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                new String[]{"TLSv1"},
                null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

            RequestConfig defaultRequestConfig = RequestConfig.custom()
                .setSocketTimeout(5000).setConnectTimeout(5000)
                .setConnectionRequestTimeout(5000)
                .setStaleConnectionCheckEnabled(true).build();

            CloseableHttpClient httpclient1 = HttpClients.custom()
                .setDefaultRequestConfig(defaultRequestConfig)
                .setSSLSocketFactory(sslsf).build();

            HttpPost httpost = new HttpPost(url);

            // DefaultHttpClient httpclient = (DefaultHttpClient)
            // HttpClientConnectionManager.getSSLInstance(httpclient1);

            // HttpPost httpost = new HttpPost(url);

            httpost.addHeader("Connection", "keep-alive");
            httpost.addHeader("Accept", "*/*");
            httpost.addHeader("Content-Type",
                "application/x-www-form-urlencoded; charset=UTF-8");
            httpost.addHeader("Host", "api.mch.weixin.qq.com");
            httpost.addHeader("X-Requested-With", "XMLHttpRequest");
            httpost.addHeader("Cache-Control", "max-age=0");
            httpost.addHeader("User-Agent",
                "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
            httpost.setEntity(new StringEntity(xmlParam, "UTF-8"));
            // System.out.println("executing request" +
            // httpost.getRequestLine());

            CloseableHttpResponse response = httpclient1.execute(httpost);
            try {
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    // System.out.println("Response content length: " +
                    // entity.getContentLength());
                    BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(entity.getContent(), "UTF-8"));
                    String text;
                    while ((text = bufferedReader.readLine()) != null) {
                        message.append(text);
                    }
                }
                EntityUtils.consume(entity);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                response.close();
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        try {
            String jsonStr = message.toString();
            return doXMLParse(jsonStr);
        } catch (Exception e) {

            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解析xml,返回第一级元素键值对。如果第一级元素有子节点，则此节点的值是子节点的xml数据。
     *
     * @param strxml
     * @return
     * @throws JDOMException
     * @throws IOException
     */
    public static Map<String, String> doXMLParse(String strxml)
        throws Exception {
        if (null == strxml || "".equals(strxml)) {
            return null;
        }

        Map<String, String> m = new HashMap<String, String>();
        InputStream in = String2Inputstream(strxml);
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(in);
        Element root = doc.getRootElement();
        List list = root.getChildren();
        Iterator it = list.iterator();
        while (it.hasNext()) {
            Element e = (Element) it.next();
            String k = e.getName();
            String v = "";
            List children = e.getChildren();
            if (children.isEmpty()) {
                v = e.getTextNormalize();
            } else {
                v = getChildrenText(children);
            }

            m.put(k, v);
        }

        // 关闭流
        in.close();

        return m;
    }

    /**
     * 获取子结点的xml
     *
     * @param children
     * @return String
     */
    public static String getChildrenText(List children) {
        StringBuffer sb = new StringBuffer();
        if (!children.isEmpty()) {
            Iterator it = children.iterator();
            while (it.hasNext()) {
                Element e = (Element) it.next();
                String name = e.getName();
                String value = e.getTextNormalize();
                List list = e.getChildren();
                sb.append("<" + name + ">");
                if (!list.isEmpty()) {
                    sb.append(getChildrenText(list));
                }
                sb.append(value);
                sb.append("</" + name + ">");
            }
        }

        return sb.toString();
    }

    public static InputStream String2Inputstream(String str) {
        try {
            return new ByteArrayInputStream(str.getBytes("UTF8"));
        } catch (UnsupportedEncodingException e) {

            e.printStackTrace();
        }
        return null;
    }

    // public static void main(String[] args) {
    // String xx="<xml>"+
    // "<return_code><![CDATA[SUCCESS]]></return_code>"+
    // "<return_msg><![CDATA[参数错误:appid不属于该商户号!]]></return_msg>"+
    // "<result_code><![CDATA[FAIL]]></result_code>"+
    // "<err_code><![CDATA[PARAM_ERROR]]></err_code>"+
    // "<err_code_des><![CDATA[参数错误:appid不属于该商户号!]]></err_code_des>"+
    // "</xml>";
    // Map<String, String> map;
    // try {
    // map = doXMLParse(xx);
    // System.out.println(map);
    // System.out.println(null==map);
    // } catch (Exception e) {
    //
    // e.printStackTrace();
    // }
    //
    // }

}
